angular.module('Jason.main').controller("MainCtrl", indexCtrl);

indexCtrl.$inject = ["$scope","$compile","$rootScope","$uibModal","$sce","$http","$interval","$timeout"];



function indexCtrl($scope,$compile,$rootScope,$uibModal,$sce,$http,$interval,$timeout) {

    var iceServersObj = {"urls": "stun:127.0.0.1:9876"},//iceServer set
        connection = new WebSocket('ws://localhost:8888'), //websocket 服务器连接
        yourVideo = document.querySelector('#yours'),
        theirVideo = document.querySelector('#theirs'),
        constraints = { audio: true, video: { width: 800, height: 700 }},// 视频的大小比例
        sendPic = $("#sendPic"),
        sendFiles = $("#sendFiles"),
        recordsContainer = document.getElementById("msg_place");//聊天内容窗口

    $scope.name = null;//当前用户名ID
    $scope.connectedUser = null;//当前联系人的ID
    $scope.showVideoOperater = true; //布尔值决定是否显示操作按钮
    $scope.showHolding = false;//是否显示正在等待对方接收视频邀约

    $scope.videoRequestUserName =null;//视频请求对方名称
    $scope.loginPageShow = true;
    $scope.showEmotion = false;//显示表情
    $scope.callPageShow = false;

    $scope.emotionList = []; //表情数组






    //操作按钮
    $scope.yourConnection = null;//自己的连接RtcPeercConnection对象
    $scope.stream = null;//数据流

    //消息记录
    $scope.chatRecordsData  = null;
    $scope.showChatByVideo = false;//是否显示视频聊天界面
    $scope.showSelfVideo = true;//是否显示自己的视频


    $scope.muted = false;
    $scope.voiceMute = '静音';


    

    

    //初始化
    AdapterJS.webRTCReady(function(isUsingPlugin) {
        initpage();//初始化页面


        connection.onopen = function () {
            console.log("Connected");
        };

        // Handle all messages through this callback
        connection.onmessage = function (message) {
            console.log("Got message", message.data);

            var data = JSON.parse(message.data);

            switch (data.type) {
                case "login":
                    onLogin(data.success);
                    break;
                case "inviteChatByVideo":
                    oninviteChatByVideo(data.name);
                    break;
                case "answerInviteChatByVideo":
                    onAnswerInviteChatByVideo(data);
                    break;
                case "offer":
                    onOffer(data.offer, data.name);
                    break;
                case "answer":
                    onAnswer(data.answer);
                    break;
                case "candidate":
                    onCandidate(data.candidate);
                    break;
                case "textMsg":
                    onTextMsg(data);
                    break;
                case "img":
                    onImgMsg(data);
                    break;
                case "files":
                    onFilesMsg(data);
                    break;
                case "leave":
                    onLeave();
                    break;
                default:
                    break;
            }
            recordsContainer.scrollTop = recordsContainer.scrollHeight;
        };

        connection.onerror = function (err) {
            console.log("Got error", err);
        };



        $scope.toggleMute = function(){
            $scope.stream.getAudioTracks()[0].stop();

            $scope.muted = true;
            $scope.voiceMute = '取消静音';
            console.log("Mute your voice");

        }

        // Login when the user clicks the button


        $scope.login = function () {

            if ($scope.name.length > 0) {
                send({
                    type: "login",
                    name: $scope.name
                });
            }

            getHistoryMsg(function(records){msgToWhichSlide(records)}); ;//填写消息

        }

        $scope.startConnection = function() {

            navigator.mediaDevices.getUserMedia(constraints)
                .then(function (myStream) {
                    $scope.stream = myStream;

                    yourVideo.src = window.URL.createObjectURL($scope.stream);


                    setupPeerConnection($scope.stream);


                })
                .catch(function (error) {
                    console.log(error);
                });

        }

         $scope.inviteChatByVideo = function () {

            send({type: "inviteChatByVideo", name: $scope.connectedUser});
            $scope.startConnection();
            $scope.showHolding = true;
            $scope.showChatByVideo = true;

        }

        $scope.startPeerConnection = function() {

            // Begin the offer
            $scope.yourConnection.createOffer(function (offer) {
                send({
                    type: "offer",
                    offer: offer,
                    name:$scope.connectedUser
                });
                $scope.yourConnection.setLocalDescription(offer);


            }, function (error) {
                alert("An error has occurred.");
            });

            $scope.showHolding = true;
        };


        //sendTextMsg

        $scope.sendMsg = function () {

            var val = $scope.textMsgAreaValue.replace(new RegExp(/( )/g),"").replace(/[\r\n]/g,"");//去掉回车换行 空格;


            appendTextMsg({"from": $scope.name,"to":$scope.connectedUser,"type":"text",showText:true,"msg": val,"date":new Date},'self');
            send({
                from: $scope.name,
                to: $scope.connectedUser,
                type: "textMsg",
                showText:true,
                msg: val,
                date:new Date()
            });

        }

        $scope.enterKeyUp = function(event){
            var e = event || window.event || arguments.callee.caller.arguments[0];
            if(e && e.keyCode==27){ // 按 Esc
                //要做的事情
            }
            if(e && e.keyCode==113){ // 按 F2
                //要做的事情
            }
            if(e && e.keyCode==13){ // enter 键
                //要做的事情

                $scope.sendMsg();
            }

        }


        //切换联系人
        $scope.changeConnectedUser = function (userId) {
            var  $this = $('#'+userId);
            $this.siblings().removeClass("curChatUser");
            $this.addClass("curChatUser");
            $scope.connectedUser = $this.attr("id");

        }

        //退出视频聊天
        $scope.closeVideoChat = function(){

            send({
                type: "leave"
            });

            onLeave(true);

        }

        $scope.toggleSelfVideo = function(){
            $scope.showSelfVideo = !$scope.showSelfVideo;

        }


        //for test
        $scope.test = function(){
            var aa = navigator.mediaDevices.getUserMedia;
            console.log(aa);


            navigator.mediaDevices.getUserMedia(constraints)
                .then(function (myStream) {
                    var stream = myStream;

                    document.getElementById("testvideo").src = window.URL.createObjectURL(stream);

                    setupPeerConnection(stream);

                })
                .catch(function (error) {
                    console.log(error);
                });
        }


        $scope.showEmotionFun = function(){
            $scope.showEmotion = true;
        }


    });

    function initpage(){
        initEmotion();//初始化表情
        bindBodyClick();//绑定页面点击事件
        initSendFiles();//初始化发送文件功能
        initSendPic();//初始化发送图片功能
    }
    function initSendPic(){
        sendPic.on("change",function(e){
            //检查是否有文件被选中
            if (this.files.length != 0) {
                //获取文件并用FileReader进行读取
                var file = this.files[0],
                    reader = new FileReader();
                if (!reader) {
                    var showContent = "your browser doesn\'t support fileReader";
                    appendTextMsg({"from": $scope.name,"to":$scope.connectedUser,"type":"text","msg":showContent ,"date":new Date},'self');

                    return;
                };
                reader.onload = function(e) {
                    //读取成功，显示到页面并发送到服务器


                    appendImgMsg({"from": $scope.name,"to":$scope.connectedUser,"type":"img","msg":e.target.result ,"date":new Date},'self')
                    send({
                        from: $scope.name,
                        to: $scope.connectedUser,
                        type: "img",
                        msg: e.target.result,
                        date:new Date()
                    });

                    $scope.$digest();


                };
                reader.readAsDataURL(file);
            };
        })
    }
    
    
    function initSendFiles(){
        sendFiles.on("change",function(e){
            //检查是否有文件被选中
            if (this.files.length != 0) {
                //获取文件并用FileReader进行读取
                var file = this.files[0];
                var filename = this.files[0].name;


                var  reader = new FileReader();
                if (!reader) {
                    var showContent = "your browser doesn\'t support fileReader";
                    appendTextMsg({"from": $scope.name,"to":$scope.connectedUser,"type":"files","msg":showContent ,"date":new Date},'self');


                    return;
                };


                reader.onload = function(e) {

                    appendFiles({"from": $scope.name,"to":$scope.connectedUser,"type":"files","filename":filename,"msg":e.target.result ,"date":new Date},'self')
                    send({
                        from: $scope.name,
                        to: $scope.connectedUser,
                        type: "files",
                        filename:filename,
                        msg: e.target.result,
                        date:new Date()
                    });

                    $scope.$digest();



                };
                reader.readAsDataURL(file);
            };
        })
    }
    


    

    //初始化完毕

    function bindBodyClick(){
        var emotionOperator = document.getElementById('emotionOperator');

        document.body.addEventListener('click', function(e) {

            if (e.target != emotionOperator) {


                $scope.showEmotion = false;
                $scope.$digest();

            };
        });
    }





    //消息选择性放在左右边
    function msgToWhichSlide(records){


        for(msg in records){


            if(records[msg].from === $scope.name){
                records[msg]["slide"] = "text-right";
            }else{
                records[msg]["slide"] = "text-left";
            }

        }

    }
    //初始化表情

    function initEmotion() {

        for (var i = 1; i < 69; i++) {
            var emojiItemSrc = './src/common/img/emoji/' + i + '.gif';
            $scope.emotionList.push(emojiItemSrc);


        };


    }


    //获取历史纪录
    function getHistoryMsg(callback){

        $http.get("./records.json")
            .success(function(response) {


                $scope.chatRecordsData = response;

                callback($scope.chatRecordsData);

            });
    }
    function onImgMsg(data){
        console.log(data);
        appendImgMsg(data)

    }
    function onFilesMsg(data){
        console.log(data);
        appendFiles(data)
    }

    function oninviteChatByVideo(name) {
        console.log(" recevie inviteChatByVideo from " + name);
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: "myModalContent.html",
            controller: 'ModalInstanceCtrl',
            backdrop: false,
            size: 'sm',
            resolve: {
                videoRequestUserName: function () {
                    return $scope.videoRequestUserName;
                }
            }
        });
        modalInstance.result.then(function () {
            console.log("ok");
            send({type: "answerInviteChatByVideo", result: 'ok'});
            $scope.startConnection();
            $scope.showChatByVideo = true;
        }, function () {
            console.log("cancel");
            send({type: "answerInviteChatByVideo", result: 'cancel'});
        });
    }

    function onAnswerInviteChatByVideo(data) {
        var result = data.result;
        switch (result) {
            case 'ok':
                console.log("opposite agree by video");

                $scope.startPeerConnection();//创建连接

                break;
            case 'cancel':
                alert("您的好友入谢绝了您的视频邀请~")
                console.log("opposite not agree by video");
                break;
            default:
                console.log('answer error.');
        }
    }
    // Alias for sending messages in JSON format
    function send(message) {
        if ($scope.connectedUser) {
            message.name = $scope.connectedUser;
        }

        connection.send(JSON.stringify(message));
    };

    function onLogin(success) {
        if (success === false) {
            alert("Login unsuccessful, please try a different name.");
        } else {
            //生成用户列表
            getConnectedUserList($scope.name,function(){
                $scope.loginPageShow = false;
                $scope.callPageShow  = true;

                $scope.connectedUser = $scope.userList[0].name;




            });

        }
    };

    function setupPeerConnection(stream) {
        var configuration = {
            "iceServers": [iceServersObj]
        };
        $scope.yourConnection = new RTCPeerConnection(configuration);

        // Setup stream listening
        $scope.yourConnection.addStream(stream);

        $scope.yourConnection.ontrack = function (e) {

            theirVideo.src = window.URL.createObjectURL(e.streams[0]);
        };

        // Setup ice handling
        $scope.yourConnection.onicecandidate = function (event) {//onaddstream is deprecated! Use peerConnection.ontrack instead.
            if (event.candidate) {
                send({
                    type: "candidate",
                    candidate: event.candidate
                });
            }
        };
    }
    function onOffer(offer, name) {



        $scope.videoRequestUserName = name;

        $scope.yourConnection.setRemoteDescription(new RTCSessionDescription(offer));


        $scope.yourConnection.createAnswer(function (answer) {
            $scope.yourConnection.setLocalDescription(answer);
            send({
                type: "answer",
                answer: answer
            });
        }, function (error) {
            alert("An error has occurred");
        });


    };




    function onAnswer(answer) {
        $scope.yourConnection.setRemoteDescription(new RTCSessionDescription(answer));
        $scope.showHolding = false;
        $scope.$digest()


    };

    function onCandidate(candidate) {
        $scope.yourConnection.addIceCandidate(new RTCIceCandidate(candidate));
    };



    function onLeave(self) {
        $scope.showChatByVideo = false;
        theirVideo.src = null;
        $scope.yourConnection.close();
        $scope.yourConnection.onicecandidate = null;
        $scope.yourConnection.onaddstream = null;

        setupPeerConnection($scope.stream);
        $scope.showHolding = false;//对方已回应
        if(!self){
            $scope.$digest();
        }



    };


    //收到文本聊天后的处理
    function onTextMsg(data) {
        appendTextMsg(data);


    }


    //handle text msg
    function appendTextMsg(msgData,self) {


        if (typeof msgData != 'object') {
            msgData = JSON.parse(msgData);
        }

        msgData['avatar'] = "./build/common/img/avatar/UAPQLkQxLNKlE5Dycme69CNw88Nupa.png";
        msgData['showText'] = true;

        $scope.chatRecordsData.push(msgData);
        msgToWhichSlide($scope.chatRecordsData);

        if (self != 'self') {
            $scope.$digest();//更新$SCOPE

        }
        clear();
    }


    //handle text msg
    function appendImgMsg(msgData,self) {


        if (typeof msgData != 'object') {
            msgData = JSON.parse(msgData);
        }

        msgData['avatar'] = "./build/common/img/avatar/UAPQLkQxLNKlE5Dycme69CNw88Nupa.png";
        msgData['showImg'] = true;
        $scope.chatRecordsData.push(msgData);
        msgToWhichSlide($scope.chatRecordsData);

        if (self != 'self') {
            $scope.$digest();//更新$SCOPE

        }
        makeLastChatRecordInView();

    }


    //handle text msg
    function appendFiles(msgData,self) {


        if (typeof msgData != 'object') {
            msgData = JSON.parse(msgData);
        }

        msgData['avatar'] = "./build/common/img/avatar/UAPQLkQxLNKlE5Dycme69CNw88Nupa.png";
        msgData['showFiles'] = true;
        msgData['filename'] = msgData.filename;
        $scope.chatRecordsData.push(msgData);
        msgToWhichSlide($scope.chatRecordsData);

        if (self != 'self') {
            $scope.$digest();//更新$SCOPE

        }

        makeLastChatRecordInView();

        $timeout(deleteUnsafe,600);



    }

    function deleteUnsafe(){
        var selectorFiles = $(".recived-img");
        for(var i= 0; i< selectorFiles.length; i++){

            if(selectorFiles.eq(i).find('a').attr("href"))
                selectorFiles.eq(i).find('a').attr("href",selectorFiles.eq(i).find('a').attr("href").replace("unsafe:",''))
        }
    }


    //清除聊天框里的内容
    function clear(){
        $scope.textMsgAreaValue = '';
        //console.log(recordsContainer.scrollTop,recordsContainer.scrollHeight);

        makeLastChatRecordInView();

    }
    function makeLastChatRecordInView(){
        $timeout(function () {
            recordsContainer.scrollTop = recordsContainer.scrollHeight;
        }, 200);//hold 600 seconds

    }

    //获取当前用户的联系人列表
    function getConnectedUserList(name,callback) {


        $http.get("./usrDataJson.json")
            .success(function(response) {

                switch (name) {
                    case 'a':
                        $scope.userList = response.a;
                        break;
                    case 'b':
                        $scope.userList = response.b;
                        break;
                    case 'c':
                        $scope.userList = response.c;
                        break;

                    case 'd':
                        $scope.userList = response.d;
                        break;
                    default:
                        $scope.userList = response.a;

                }
                callback();





            });



    }

    function arrayBufferToBase64(buffer) {
        var binary = '';
        var bytes = new Uint8Array(buffer);
        var len = bytes.byteLength;
        for (var i = 0; i < len; i++) {
            binary += String.fromCharCode( bytes[ i ] );
        }
        return btoa(binary);
    }

    function base64ToBlob(b64Data, contentType) {
        contentType = contentType || '';

        var byteArrays = [], byteNumbers, slice;

        for (var i = 0; i < b64Data.length; i++) {
            slice = b64Data[i];

            byteNumbers = new Array(slice.length);
            for (var n = 0; n < slice.length; n++) {
                byteNumbers[n] = slice.charCodeAt(n);
            }

            var byteArray = new Uint8Array(byteNumbers);

            byteArrays.push(byteArray);
        }

        var blob = new Blob(byteArrays, {type: contentType});
        return blob;
    }




    $scope.emotionAddClick = function (selector){



            if($scope.textMsgAreaValue){
                $scope.textMsgAreaValue = $scope.textMsgAreaValue + '[emoji:' + selector + ']';
            }else{
                $scope.textMsgAreaValue = '[emoji:' + selector + ']';
            }





    }






}



// Please note that $uibModalInstance represents a modal window (instance) dependency.
// It is not the same as the $uibModal service used above.

angular.module('Jason.main').controller("ModalInstanceCtrl",function ($scope, $uibModalInstance, videoRequestUserName) {

    $scope.videoRequestUserName = videoRequestUserName;

    $scope.ok = function () {
        $uibModalInstance.close();
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
});
